import os
from datetime import timedelta
from dotenv import load_dotenv
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
if os.path.exists(env_path):
    load_dotenv(env_path)
    logger.info(f"Loaded environment variables from {env_path}")
else:
    logger.warning(f"No .env file found at {env_path}")

class BaseConfig:
    SECRET_KEY = os.getenv('SECRET_KEY', 'dev-key-please-change')
    DEBUG = False
    TESTING = False
    
    DASHSCOPE_API_KEY = os.getenv('DASHSCOPE_API_KEY')
    API_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
    API_TIMEOUT = 30
    
    # 默认模型名
    MODEL_NAME = "qwen2.5-math-7b-instruct"
    # 可用模型列表，示例
    AVAILABLE_MODELS = [
        "qwen2.5-math-7b-instruct",
        "qwen-plus",
        "qwen-turbo",
        "qwen2.5-72b-instruct"

    ]

    @property
    def API_HEADERS(self):
        if not self.DASHSCOPE_API_KEY:
            logger.error("DASHSCOPE_API_KEY not found in environment variables")
            raise ValueError("DASHSCOPE_API_KEY must be set")
        return {
            'Authorization': f'Bearer {self.DASHSCOPE_API_KEY}',
            'Content-Type': 'application/json'
        }
    
    MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16MB
    MAX_MESSAGE_LENGTH = 2000
    MAX_CONVERSATION_LENGTH = 50
    
    RATE_LIMIT = {
        'DEFAULT': {'requests': 60, 'window': 60},
        'API': {'requests': 100, 'window': 60}
    }

    CORS_ORIGINS = os.getenv('CORS_ORIGINS', '*').split(',')
    SYSTEM_PROMPT = "你是一个有帮助的AI助手。请用简短、清晰、友好的方式回答问题。"

    SESSION_COOKIE_SECURE = True
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = 'Lax'
    PERMANENT_SESSION_LIFETIME = timedelta(days=7)

class DevelopmentConfig(BaseConfig):
    DEBUG = True
    TESTING = True
    SESSION_COOKIE_SECURE = False
    
    def __init__(self):
        super().__init__()
        logger.info("Loading development configuration")

class ProductionConfig(BaseConfig):
    def __init__(self):
        super().__init__()
        logger.info("Loading production configuration")
        if not self.DASHSCOPE_API_KEY:
            logger.error("DASHSCOPE_API_KEY not set in production environment")
            raise ValueError("DASHSCOPE_API_KEY must be set in production")

config_by_name = {
    'development': DevelopmentConfig,
    'production': ProductionConfig,
    'default': DevelopmentConfig
}

def get_config(config_name=None):
    if not config_name:
        config_name = os.getenv('FLASK_ENV', 'default')
    return config_by_name.get(config_name, config_by_name['default'])()
